package cn.hd01.web.auth;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class AuthDelegate {

	private Map<AuthType, Authenticator> authMap = new HashMap<AuthType, Authenticator>();

	public boolean authenticate(HttpServletRequest request, HttpServletResponse response, AuthType type)
			throws Exception {
		if (!authMap.containsKey(type)) {
			response.sendError(HttpStatus.NOT_FOUND.value());
			return false;
		}

		return authMap.get(type).authenticate(request, response);
	}

	@Autowired(required = false)
	public void setAuthenticators(List<Authenticator> authenticators) {
		for (Authenticator authenticator : authenticators) {
			authMap.put(authenticator.type(), authenticator);
		}
	}
}
